package com.bawei.mdm2207alast.sign

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.SDKInitializer
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.bawei.mdm2207alast.App
import com.bawei.mdm2207alast.base.OnError
import com.bawei.mdm2207alast.base.OnLoading
import com.bawei.mdm2207alast.base.OnSuccess
import com.bawei.mdm2207alast.common.BaseTitle
import com.bawei.mdm2207alast.model.FormatUtils
import com.bawei.mdm2207alast.model.InsertSignEntity
import com.blankj.utilcode.util.ToastUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.webrtc.ContextUtils.getApplicationContext
import java.text.SimpleDateFormat
import java.util.Date


/**
 * 作者：赵亮
 * 时间：2024/12/16 15:38
 * 功能：签到页面
 */
lateinit var mapView: MapView
lateinit var baiduMap: BaiduMap
lateinit var mLocationClient: LocationClient
var longitude = 116.318389
var latitude = 39.978021

@Composable
fun InsertSignPage(
    navController: NavController = rememberNavController(),
    viewModel: SignViewModel = hiltViewModel()
) {

    // 打卡 动态时间
    var time by remember {
        mutableStateOf(Date())
    }

    val dateFormat = SimpleDateFormat("hh:mm:ss")

    var signState by remember {
        mutableStateOf("上班打卡")
    }
    var goToWorkTime by remember {
        mutableStateOf("上班还未打卡")
    }
    var goOffWorkTime by remember {
        mutableStateOf("下班还未打卡")
    }

    val mmkv = MMKV.defaultMMKV()
    val isSign = mmkv.decodeString("sign", "").toString()
    if (!isSign.isEmpty()) {
        val split = isSign.split(",")
        val format = SimpleDateFormat("yyyy-MM-dd")
        if (format.format(System.currentTimeMillis()) == format.format(split[1].toLong())) {
            goToWorkTime = SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(split[1])
            signState = "下班打卡"
        }
    }


    LaunchedEffect(key1 = "") {
        launch {
            while (true) {
                delay(1000)
                time = Date()
            }
        }
        launch {
            viewModel.uiState.collect {
                when (it) {
                    is OnError -> {
                        ToastUtils.showShort(it.msg)
                    }

                    OnLoading -> {}
                    is OnSuccess<*> -> {
                        ToastUtils.showShort((it.data as InsertSignEntity).msg)

                        // 存储签到状态
                        if (!isSign.isEmpty()) {
                            val split = isSign.split(",")
                            val format = SimpleDateFormat("yyyy-MM-dd")
                            if (format.format(System.currentTimeMillis()) == format.format(split[1].toLong())) {
                                mmkv.encode("sign", "签退,${System.currentTimeMillis()}")
                            } else {
                                mmkv.encode("sign", "签到,${System.currentTimeMillis()}")
                            }
                        } else { // 第一次使用软件
                            mmkv.encode("sign", "签到,${System.currentTimeMillis()}")
                        }

                        navController.popBackStack()
                    }
                }
            }
        }
    }

    Column {
        // 标题
        Box(modifier = Modifier.fillMaxWidth()) {
            BaseTitle(navController = navController, title = "签到")
            Box(
                modifier = Modifier
                    .padding(top = 24.dp, end = 15.dp)
                    .size(50.dp, 25.dp)
                    .background(color = Color.Blue, shape = RoundedCornerShape(10.dp))
                    .align(Alignment.CenterEnd)
                    .clickable {
                        // 发送签到的意图
                        viewModel.sendIntent(
                            SignIntent.InsertSign(
                                mapOf(
                                    "userId" to 1,
                                    "SignLat" to 1.1,
                                    "SignLong" to 1.1,
                                    "signTime" to 1
                                )
                            )
                        )
                    }
            ) {
                Text(
                    text = "确定",
                    color = Color.White,
                    modifier = Modifier
                        .align(Alignment.Center)
                )
            }
        }

        Column {
            initBaiDuMap()
            // 地图
            AndroidView(modifier = Modifier.weight(1f), factory = {
                mapView = MapView(it)
                baiduMap = mapView.map
                baiduMap.isMyLocationEnabled = true
                mapView
            })
            // 打卡记录
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 30.dp)
                    .fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(10.dp)
            ) {

                Text(text = goToWorkTime)
                Text(text = goOffWorkTime)
                Button(modifier = Modifier
                    .size(130.dp)
                    .align(Alignment.CenterHorizontally), onClick = {
                    // 存储签到状态
                    if (signState == "上班打卡") {
                        signState = "下班打卡"
                        goToWorkTime =
                            "上班时间：${FormatUtils.formatTime.format(System.currentTimeMillis())}"
                    } else {
                        goOffWorkTime =
                            "下班时间：${FormatUtils.formatTime.format(System.currentTimeMillis())}"
                    }
                }) {
                    Text(text = "${signState}\n${dateFormat.format(time)}")
                }
            }
        }
    }
}

fun initBaiDuMap() {
    // 设置隐私模式
    SDKInitializer.setAgreePrivacy(App.context, true)
    // 初始化百度地图
    SDKInitializer.initialize(App.context)


    // 设置定位的隐式模式
    LocationClient.setAgreePrivacy(true)
    //定位初始化
    mLocationClient = LocationClient(App.context)

    //通过LocationClientOption设置LocationClient相关参数
    val option = LocationClientOption()
    option.isOpenGps = true // 打开gps
    option.setCoorType("bd09ll") // 设置坐标类型
    option.setScanSpan(1000)


    //设置locationClientOption
    mLocationClient.setLocOption(option)


    //注册LocationListener监听器
    val myLocationListener = MyLocationListener()
    mLocationClient.registerLocationListener(myLocationListener)

    //开启地图定位图层
    mLocationClient.start()
}

class MyLocationListener : BDAbstractLocationListener() {
    override fun onReceiveLocation(location: BDLocation) {
        //mapView 销毁后不在处理新接收的位置
        if (location == null || mapView == null) {
            return
        }

        // 给地图添加定位小蓝点
        baiduMap.animateMapStatus(
            MapStatusUpdateFactory.newLatLngZoom(
                LatLng(latitude, longitude),
                18f
            )
        )

        val locData = MyLocationData.Builder()
            .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
            .direction(location.direction).latitude(latitude)
            .longitude(longitude).build()
        baiduMap.setMyLocationData(locData)
    }
}

@Preview
@Composable
fun InsertSignPagePreview() {
    InsertSignPage()
}

